package org.itstack.demo.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.itstack.demo.netty.util.MsgUtil;

public class NettyClient {

    public static void main(String[] args) {

        new NettyClient().connect("127.0.0.1", 7397);
    }

    private void connect(String inetHost, int inetPort) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.AUTO_READ, true)
                    .handler(new MyChannelInitializer());

            ChannelFuture channelFuture = bootstrap.connect(inetHost, inetPort).sync();

            System.out.println("netty client start done!");

            //测试消息，分别发放demo01、demo02、demo03
            channelFuture.channel().writeAndFlush(MsgUtil.buildMsgDemo01(channelFuture.channel().id().toString(),"你好，消息体MsgDemo01，我是乌尔奇奥拉。"));
            channelFuture.channel().writeAndFlush(MsgUtil.buildMsgDemo02(channelFuture.channel().id().toString(),"你好，消息体MsgDemo02，我是乌尔奇奥拉。"));
            channelFuture.channel().writeAndFlush(MsgUtil.buildMsgDemo03(channelFuture.channel().id().toString(),"你好，消息体MsgDemo03，我是乌尔奇奥拉。"));


            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }

    }
}
